import { api } from './api'
import type { ApiResponse, PaginatedResponse, PaginationParams } from '../types'

interface Comment {
  id: number
  content: string
  articleId: number
  parentId?: number
  author: {
    id: number
    username: string
    avatar?: string
  }
  replies?: Comment[]
  createdAt: string
  updatedAt: string
}

interface CreateCommentRequest {
  content: string
  articleId: number
  parentId?: number
}

interface UpdateCommentRequest {
  content: string
}

interface GetCommentsParams extends PaginationParams {
  articleId?: number
  userId?: number
}

export const commentsApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getComments: builder.query<ApiResponse<PaginatedResponse<Comment>>, GetCommentsParams>({
      query: (params) => ({
        url: '/comments',
        params,
      }),
      providesTags: (result) =>
        result
          ? [
              ...result.data.content.map(({ id }) => ({ type: 'Comment' as const, id })),
              { type: 'Comment' as const, id: 'LIST' },
            ]
          : [{ type: 'Comment' as const, id: 'LIST' }],
    }),

    getComment: builder.query<ApiResponse<Comment>, number>({
      query: (id) => `/comments/${id}`,
      providesTags: (result) =>
        result ? [{ type: 'Comment' as const, id: result.data.id }] : [],
    }),

    createComment: builder.mutation<ApiResponse<Comment>, CreateCommentRequest>({
      query: (data) => ({
        url: '/comments',
        method: 'POST',
        body: data,
      }),
      invalidatesTags: (result) =>
        result
          ? [
              { type: 'Comment', id: 'LIST' },
              { type: 'Article', id: result.data.articleId },
            ]
          : [{ type: 'Comment', id: 'LIST' }],
    }),

    updateComment: builder.mutation<ApiResponse<Comment>, { id: number; data: UpdateCommentRequest }>({
      query: ({ id, data }) => ({
        url: `/comments/${id}`,
        method: 'PUT',
        body: data,
      }),
      invalidatesTags: (result) =>
        result ? [{ type: 'Comment', id: result.data.id }] : [],
    }),

    deleteComment: builder.mutation<ApiResponse<void>, number>({
      query: (id) => ({
        url: `/comments/${id}`,
        method: 'DELETE',
      }),
      invalidatesTags: [{ type: 'Comment', id: 'LIST' }],
    }),

    getReplies: builder.query<ApiResponse<Comment[]>, number>({
      query: (commentId) => `/comments/${commentId}/replies`,
      providesTags: (result) =>
        result
          ? [
              ...result.data.map(({ id }) => ({ type: 'Comment' as const, id })),
              { type: 'Comment' as const, id: 'LIST' },
            ]
          : [{ type: 'Comment' as const, id: 'LIST' }],
    }),
  }),
})

export const {
  useGetCommentsQuery,
  useGetCommentQuery,
  useCreateCommentMutation,
  useUpdateCommentMutation,
  useDeleteCommentMutation,
  useGetRepliesQuery,
} = commentsApi 